package com.example.stlink.activitys.fragmentChild.activityTeaHome;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.bumptech.glide.Glide;
import com.example.stlink.R;
import com.example.stlink.configs.GlideEngine;
import com.example.stlink.model.constants.ModelFieldConstants;
import com.example.stlink.model.constants.UrlConstants;
import com.example.stlink.model.request.CourseCreateRequest;
import com.example.stlink.utils.CommonUtils;
import com.example.stlink.utils.activityUtil.CreateCourseUtil;
import com.example.stlink.utils.activityUtil.ImgUploadUtil;
import com.google.android.material.datepicker.MaterialDatePicker;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.google.android.material.textfield.TextInputEditText;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.config.SelectModeConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;

import java.util.ArrayList;
import java.util.Objects;

public class CreateCourse extends AppCompatActivity {

    private ImageView abIvTitle;
    private TextInputEditText etCourseName;
    private ImageView ivAddImg;
    private TextInputEditText etCourseDescription;
    private TextInputEditText etStartTime;
    private TextInputEditText etEndTime;
    private TextInputEditText etCreateTime;
    private TextInputEditText etStatus;
    private Button btCreateCourse;

    private boolean isSuccessCoursePhoto;
    private boolean isSuccessCourseStartTime;
    private boolean isSuccessCourseEndTime;
    private boolean isSuccessCourseCreateTime;

    private MaterialDatePicker<Long> startDatePicker;
    private MaterialDatePicker<Long> endDatePicker;
    private Bundle bundle;

    private Handler btAddHandler;

    private Handler imgUploadHandler;

    //每两秒进行一个检测
    private final Runnable btRunnable = new Runnable() {
        @SuppressLint("ResourceAsColor")
        @Override
        public void run() {
            //如果所有信息都已经添加成功之后，才启用按钮，=
            if(isSuccessCoursePhoto && isSuccessCourseStartTime && isSuccessCourseEndTime && isSuccessCourseCreateTime){
                System.out.println("Here...............................1");
                String courseName = Objects.requireNonNull(etCourseName.getText()).toString();
                String courseIntroduce = Objects.requireNonNull(etCourseDescription.getText()).toString();
                Bundle bundle1 = getIntent().getExtras();
                bundle1.putString(ModelFieldConstants.COURSE_NAME, courseName);
                bundle1.putString(ModelFieldConstants.INTRODUCE, courseIntroduce);
                getIntent().putExtras(bundle1);
                //课程名和课程简介不能为空
                if(!TextUtils.isEmpty(courseName) && !TextUtils.isEmpty(courseIntroduce)){
                    System.out.println("Here...............................2");
                    Bundle bundle2 = getIntent().getExtras();
                    long startTime = bundle2.getLong(ModelFieldConstants.START_TIME);
                    long endTime = bundle2.getLong(ModelFieldConstants.END_TIME);
                    System.out.println("startTime == " + startTime + "..........................");
                    System.out.println("endTime == " + endTime + "...........................");
                    //结束时间要在开始时间之后
                    String courseStatus = Objects.requireNonNull(etStatus.getText()).toString();
                    boolean isFinished = "已结课".equals(courseStatus);
                    if((!isFinished && (startTime < endTime)) || (isFinished && (startTime >= endTime))){
                        System.out.println("Here...............................3");
                        //启用按钮
                        btCreateCourse.setEnabled(true);
                        //更改按钮样式
                        btCreateCourse.setBackgroundResource(R.drawable.selector_bottom_add_course);
                        btCreateCourse.setTextColor(Color.WHITE);
                        //按钮事件
                        btCreateCourse.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                System.out.println("createCourse.............");
                                Handler handler = new Handler(Looper.getMainLooper()){
                                    @Override
                                    public void handleMessage(@NonNull Message msg) {
                                        super.handleMessage(msg);
                                        if ("success".equals(msg.obj)){
                                            System.out.println("添加成功...........");
                                            Toast.makeText(CreateCourse.this, "创建成功", Toast.LENGTH_SHORT).show();
                                            btAddHandler.removeCallbacks(btRunnable);
                                            finish();
                                        } else {
                                            Toast.makeText(CreateCourse.this, msg.obj.toString(), Toast.LENGTH_SHORT).show();
                                        }
                                    }
                                };
                                CreateCourseUtil.createCourse(CreateCourse.this, getCourseRequest(), handler, UrlConstants.TEACHER_COURSE);
                            }
                        });
                    }else {
                        //禁用按钮
                        btCreateCourse.setEnabled(false);
                    }
                }else {
                    //禁用按钮
                    btCreateCourse.setEnabled(false);
                }
            }else{
                //禁用按钮
                btCreateCourse.setEnabled(false);
            }
            btAddHandler.postDelayed(this, 2000);
        }
    };


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tea_create_course);

        initView();

        btAddHandler.postDelayed(btRunnable, 2000);
    }

    /**
     * 初始化活动
     */
    private void initView(){
        CommonUtils.changeStatusBar(this);

        btAddHandler = new Handler();

        isSuccessCoursePhoto = false;
        isSuccessCourseStartTime = false;
        isSuccessCourseEndTime = false;
        isSuccessCourseCreateTime = false;

        abIvTitle = findViewById(R.id.ab_iv_title);
        etCourseName = findViewById(R.id.et_course_name);
        ivAddImg = findViewById(R.id.iv_add_img);
        etCourseDescription = findViewById(R.id.et_course_description);
        etStartTime = findViewById(R.id.et_start_time);
        etEndTime = findViewById(R.id.et_end_time);
        etCreateTime = findViewById(R.id.et_create_time);
        etStatus = findViewById(R.id.et_status);
        btCreateCourse = findViewById(R.id.bt_create_course);

        startDatePicker = MaterialDatePicker.Builder.datePicker()
            .setTitleText("SELECT DATE")
            .setSelection(MaterialDatePicker.todayInUtcMilliseconds())
            .build();
        endDatePicker = MaterialDatePicker.Builder.datePicker()
                .setTitleText("SELECT DATE")
                .setSelection(MaterialDatePicker.todayInUtcMilliseconds())
                .build();

        btCreateCourse.setEnabled(false);

        refreshData();

        // 用于图片上传成功之后刷新界面
        imgUploadHandler = new Handler(Looper.getMainLooper()){
                @Override
                public void handleMessage(@NonNull Message msg) {
                    super.handleMessage(msg);
                    bundle = (Bundle) msg.obj;
                    if(bundle.getBoolean(UrlConstants.IS_IMG_UPLOAD_SUCCESS)){
                        System.out.println("refreshData..................");
                        getIntent().putExtras(bundle);
                        refreshData();
                        //表示照片添加成功
                        isSuccessCoursePhoto = true;
                    }else{
                        Toast.makeText(CreateCourse.this, "修改失败", Toast.LENGTH_SHORT).show();
                    }
                }
            };

        setClickListener();
    }

    private void refreshData(){


        bundle = getIntent().getExtras();
        String courseImg = bundle.getString(ModelFieldConstants.COURSE_PHOTO);
        if(courseImg != null){  // 将图片加载出来
            Glide.with(getApplicationContext())
                    .load(courseImg)
                    .into(ivAddImg);
        }

        //不可粘贴，长按不会弹出粘贴框
        etStartTime.setKeyListener(null);
        etEndTime.setKeyListener(null);
        etCreateTime.setKeyListener(null);
        etStatus.setKeyListener(null);
    }

    /**
     * 添加点击事件
     */
    private void setClickListener(){
        startDatePicker.addOnPositiveButtonClickListener(selection -> {
            String startFormDate = CommonUtils.stampToDate(String.valueOf(selection), "yyyy年MM月dd日");
            etStartTime.setText(startFormDate);
            isSuccessCourseStartTime = true;
            Bundle bundle1 = getIntent().getExtras();
            bundle1.putLong(ModelFieldConstants.START_TIME, selection);
            getIntent().putExtras(bundle1);
        });
        endDatePicker.addOnPositiveButtonClickListener(selection -> {
            String endFormDate = CommonUtils.stampToDate(String.valueOf(selection), "yyyy年MM月dd日");
            etEndTime.setText(endFormDate);
            isSuccessCourseEndTime = true;
            Bundle bundle1 = getIntent().getExtras();
            bundle1.putLong(ModelFieldConstants.END_TIME, selection);
            getIntent().putExtras(bundle1);
        });
        //点击添加图片
        ivAddImg.setOnClickListener(v -> {
            // 调用第三方开源图片库
            PictureSelector.create(this)
                    .openGallery(SelectMimeType.ofImage())
                    .setImageEngine(GlideEngine.createGlideEngine())    // 图片加载引擎
                    .setMaxSelectNum(1)// 最大图片选择数量 int
                    .setImageSpanCount(4)// 每行显示个数 int
                    .setSelectionMode(SelectModeConfig.SINGLE)// 多选 or 单选
                    .isPreviewImage(true)// 是否可预览图片 true or false
                    .isSelectZoomAnim(true)// 图片列表点击 缩放效果 默认true
                    .isGif(false) //是否显示gif文件
                    .isWebp(false) //是否显示webp文件
                    .isBmp(false) //是否显示bmp文件
                    .isMaxSelectEnabledMask(true) //达到最大选择数是否开启禁选蒙层
                    .forResult(new OnResultCallbackListener<LocalMedia>() {
                        @Override
                        public void onResult(ArrayList<LocalMedia> result) {    // 选择图片后回调
                            LocalMedia localMedia = result.get(0);
                            ImgUploadUtil.userImgUpload(bundle, imgUploadHandler, localMedia.getRealPath(), ModelFieldConstants.COURSE_PHOTO);
                        }
                        @Override
                        public void onCancel() { }  // 取消
                    });
        });
        //课程开始时间
        etStartTime.setOnClickListener(v -> {
            if(!startDatePicker.isAdded()){
                startDatePicker.show(getSupportFragmentManager(), "Hello");
            }
        });
        //课程结束时间
        etEndTime.setOnClickListener(v -> {
            if(!endDatePicker.isAdded()){
                endDatePicker.show(getSupportFragmentManager(), "Hello");
            }

        });
        //刷新当前时间
        etCreateTime.setOnClickListener(v -> {
            long currentDate = System.currentTimeMillis();
            String curFormDate = CommonUtils.stampToDate(String.valueOf(currentDate), "yyyy年MM月dd日");
            etCreateTime.setText(curFormDate);
            isSuccessCourseCreateTime = true;
        });
        //课程状态选择
        etStatus.setOnClickListener(v -> {
            String[] singleItems = {"未结课", "已结课"};
            int checkedItem = "未结课".equals(Objects.requireNonNull(etStatus.getText()).toString()) ? 0 : 1;

            MaterialAlertDialogBuilder materialAlertDialogBuilder = new MaterialAlertDialogBuilder(CreateCourse.this)
                    .setTitle("请选择课程授课状态")
                    .setNeutralButton(getString(R.string.cancel), (dialog, which) -> {

                    })
                    .setPositiveButton(getString(R.string.ok), (dialog, which) ->
                            etStatus.setText(singleItems[bundle.getInt("checkedItem")]))
                    .setSingleChoiceItems(singleItems, checkedItem, (dialog, which) ->
                            bundle.putInt("checkedItem", which));
            materialAlertDialogBuilder.show();
        });

        //返回上一个活动
        abIvTitle.setOnClickListener(v -> finish());
    }

    /**
     * 获取courseRequest请求实例类
     * @return 返回courseRequest封装好后的实例
     */
    private CourseCreateRequest getCourseRequest(){
        CourseCreateRequest courseCreateRequest = new CourseCreateRequest();
        bundle = getIntent().getExtras();
        String collegeName = bundle.getString(ModelFieldConstants.COLLEGE_NAME);
        String courseName = bundle.getString(ModelFieldConstants.COURSE_NAME);
        String coursePhoto = bundle.getString(ModelFieldConstants.COURSE_PHOTO);
        Long endTime = bundle.getLong(ModelFieldConstants.END_TIME);
        String introduce = bundle.getString(ModelFieldConstants.INTRODUCE);
        String realName = bundle.getString(ModelFieldConstants.REAL_NAME);
        Long startTime = bundle.getLong(ModelFieldConstants.START_TIME);
        Long userId = bundle.getLong(ModelFieldConstants.ID);
        String username = bundle.getString(ModelFieldConstants.USER_NAME);

        courseCreateRequest.setCollegeName(collegeName);
        courseCreateRequest.setCourseName(courseName);
        courseCreateRequest.setCoursePhoto(coursePhoto);
        courseCreateRequest.setEndTime(endTime);
        courseCreateRequest.setIntroduce(introduce);
        courseCreateRequest.setRealName(realName);
        courseCreateRequest.setStartTime(startTime);
        courseCreateRequest.setUserId(userId);
        courseCreateRequest.setUserName(username);

        return courseCreateRequest;
    }
}
